package com.jiuzhe.commercial.ui.house.editor;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Tip;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.HouseStayBean;
import com.jiuzhe.commercial.bean.HouseStayListBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.utils.RxBus;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by huanghao on 2018/6/7.
 */

public class EditorHomeLocationActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.map)
    MapView mMap;
    @BindView(R.id.tv_location)
    EditText tvLocation;
    @BindView(R.id.iv_center_location)
    ImageView mIvCenterLocation;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;
    private AMap mAmap;
    private int lat;
    private int lng;
    private LatLng latLng;
    private ObjectAnimator mTransAnimator;//地图中心标志动态
    private float zoom = 16;//地图缩放级别
    private UiSettings mUiSettings;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    private Tip tip;
    private LatLonPoint point;
    private String name;
    private String roomNum,regionId;
    private HouseStayListBean houseStayListBean;
    private HouseStayBean houseStayBean =  new HouseStayBean();
    private String city;
    private String area,houseArea;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_editor_home_location);
        setTitle("地图显示位置");
        setRringTitle("保存");
        tip = getIntent().getParcelableExtra("tip");
        city = getIntent().getStringExtra("city");
        area = getIntent().getStringExtra("area");
        roomNum = getIntent().getStringExtra("roomNum");
        houseArea = getIntent().getStringExtra("houseArea");
        if(null != tip) {
            point = tip.getPoint();
            name = tip.getAddress();
            String location = tip.getDistrict() + name;
            tvLocation.setText(location);
            tvLocation.setSelection(location.length());
        }else {
            lat = Constants.HOUSESTAYLISTBEAN.getLat();
            lng = Constants.HOUSESTAYLISTBEAN.getLng();
            String location = houseArea;
            tvLocation.setText(location);
            tvLocation.setSelection(location.length());
        }
        setOnClik();
    }

    private void setOnClik() {
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addHomeStayLocation();

            }
        });
    }




    private void initListener() {
        mAmap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (null != cameraPosition ) {
                // mIvLocation.setImageResource(R.mipmap.location_gps_green);
                    if (null != mAmap)
                     mAmap.clear();
                     houseStayBean.setLat((int)((cameraPosition.target.latitude)*1000000));
                     houseStayBean.setLng((int)((cameraPosition.target.longitude)*1000000));
                //  getAddressInfoByLatLong(cameraPosition.target.latitude, cameraPosition.target.longitude);
                    startTransAnimator();
                }
            }

            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mMap.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMap.onPause();
    }



    /**
     * 移动动画
     */
    private void startTransAnimator() {
        if (null != mTransAnimator && !mTransAnimator.isRunning()) {
            mTransAnimator.start();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDatas(savedInstanceState);
        houseStayListBean = new HouseStayListBean();
        initListener();
      //  startLocation();
        getMapLoation();
    }



    private void initDatas(Bundle savedInstanceState) {
        mMap.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (mAmap == null) {
            mAmap = mMap.getMap();
        }
        mUiSettings = mAmap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);//是否显示地图中放大缩小按钮
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        mUiSettings.setScaleControlsEnabled(true);//是否显示缩放级别
        mAmap.setMyLocationEnabled(false);// 是否可触发定位并显示定位层


        mTransAnimator = ObjectAnimator.ofFloat(mIvCenterLocation, "translationY", 0f, -80f, 0f);
        mTransAnimator.setDuration(1800);
    }

    private void startLocation() {
        initLocation();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
      //  locationClient.startLocation();
    }

    private void initLocation() {
        if (null == locationClient) {
            //初始化client
            locationClient = new AMapLocationClient(this.getApplicationContext());
            // 设置定位模式为低功耗模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            // 设置定位监听
            locationClient.setLocationListener(this);
          //  locationOption.setOnceLocation(true);//设置为单次定位
            // 设置定位监听
            locationClient.setLocationListener(this);
        }
    }




    @Override
    protected void loadData() {


    }

    private void moveCenter(LatLng latLng) {
        //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
      //  CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 30, 0));
        //AMap类中提供，直接移动过去，不带移动过程动画
       // mAmap.moveCamera(mCameraUpdate);
        if (null != mAmap) {
            mAmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        }
    }

    private void getMapLoation() {
        if (null != tip){
            latLng = new LatLng(point.getLatitude(), point.getLongitude()); //位置
        }else {
            latLng = new LatLng(Double.valueOf(lat) * 0.000001, Double.valueOf(lng) * 0.000001);
        }
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_market)); //图标
        markerOptions.position(latLng); //位置
        markerOptions.period(60); //设置多少帧刷新一次图片资源
        mAmap.addMarker(markerOptions);
        mAmap.clear();
        moveCenter(latLng);
       // mAmap.moveCamera(CameraUpdateFactory.zoomTo(17));
    }

    @OnClick({R.id.tv_editor})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_editor:
                if (!TextUtils.isEmpty(lat + "")) {
                    UIUtils.startActivity(EditorHomeStayMapLocationActivity.class);
                    finish();
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation loc) {
        try {
            if (null != loc) {
                stopLocation();
                if (loc.getErrorCode() == 0) {//可在其中解析amapLocation获取相应内容。
                  //  location = loc;
                  //  SPUtils.putString(MainActivity.this, DatasKey.LOCATION_INFO, gson.toJson(location));
                    mAmap.clear();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + loc.getErrorCode() + ", errInfo:"
                            + loc.getErrorInfo());

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    private void stopLocation() {
        if (null != locationClient) {
            locationClient.stopLocation();
        }
    }

    @OnClick({R.id.iv_location})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.iv_location:
                mIvLocation.setImageResource(R.mipmap.location_gps_green);
                if (null != tip){
                    latLng = new LatLng(point.getLatitude(), point.getLongitude()); //位置
                    houseStayBean.setLat((int)(point.getLatitude()*1000000));
                    houseStayBean.setLng((int)(point.getLongitude()*1000000));
                }else {
                    latLng = new LatLng(Double.valueOf(lat) * 0.000001, Double.valueOf(lng) * 0.000001);
                    houseStayBean.setLat(lat);
                    houseStayBean.setLng(lng);
                }
                moveCenter(latLng);

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLocation();
        if (null != locationClient) {
            locationClient.onDestroy();
        }
        if (mAmap != null){
            mAmap = null;
        }
        if (mMap != null){
            mMap = null;
        }
    }

    private void addHomeStayLocation() {
        String address = tvLocation.getText().toString().trim();
        HashMap<String, String> map = new HashMap<>();
        String token = SPUtil.getString(EditorHomeLocationActivity.this, Constants.TOKEN);
        String id = SPUtil.getString(EditorHomeLocationActivity.this, Constants.ID);
        String autoSignStr = Constants.SKUUPDATING.substring(Constants.SKUUPDATING.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        map.put("skuId", Constants.HOUSESTAYLISTBEAN.getId());
            map.put("address", address);
            map.put("roomNo", roomNum);
                map.put("cityName", city);
                map.put("area", area);


            map.put("lat", houseStayBean.getLat() + "");
            map.put("lng", houseStayBean.getLng() + "");

        HttpClient.post(this, Constants.SKUUPDATING, map, new CallBack<String>() {
            @Override
            public void onSuccess(String result) {
                UIUtils.showToastSafe("保存成功");
                RxBus.getInstance().post(houseStayListBean);
               // Intent intent = new Intent(EditorHomeLocationActivity.this, EditorHomeStayActivity.class);
               // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               // startActivity(intent);
                finish();
            }
        });
    }
}
